package com.bml.architect.filter;

import com.bml.architect.utils.MqConstants;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 * 在大多数情况下，可以使用Message的Tag属性来简单快速的过滤信息。
 * TAG是RocketMQ中特有的一个消息属性。RocketMQ的最佳实践中就建议，使用RocketMQ时，
 * 一个应用可以就用一个Topic，而应用中的不同业务就用TAG来区分
 */
public class TagFilterProducer {

    public static void main(String[] args) {
        DefaultMQProducer producer = new DefaultMQProducer("filterProducerGroup");
        try {
            producer.setNamesrvAddr(MqConstants.getNameServerAddr());
            producer.start();
            String tags[] = new String[]{"TAGA", "TAGB", "TAGC"};
            for (int i = 0; i < 10; i++) {
                Message message = new Message("TopicTest", tags[i % tags.length], ("rocketMq tag filter" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult send = producer.send(message);
                if (send.getSendStatus().equals(SendStatus.SEND_OK)) {
                    System.out.println("消息发送成功 " + i);
                }
            }
            producer.shutdown();
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        }


    }
}
